package service

import (
	"errors"
	"goscan-mgt/model"
	"goscan-mgt/repository"
	"goscan-mgt/utils"
	"strconv"
	"time"
)

// ScanService 提供与扫描结果相关的业务逻辑
type ScanService struct {
	repo *repository.ScanResultRepository // 扫描结果仓库
}

// NewScanService 创建一个新的 ScanService 实例
func NewScanService() *ScanService {
	repo := repository.NewScanResultRepository() // 获取扫描结果仓库实例
	return &ScanService{repo: repo}
}

// CreateScanResult 创建新的扫描结果
func (s *ScanService) CreateScanResult(scanResult *model.ScanResult) error {
	// 设置创建时间
	scanResult.CreateTime = time.Now()
	return s.repo.Create(scanResult)
}

// GetScanResultByID 根据ID获取扫描结果
func (s *ScanService) GetScanResultByID(id uint) (*model.ScanResult, error) {
	return s.repo.GetByID(id)
}

// UpdateScanResult 更新扫描结果
func (s *ScanService) UpdateScanResult(scanResult *model.ScanResult) error {
	if scanResult.ID == 0 {
		return errors.New("无效的扫描结果ID")
	}
	// 更新数据库
	return s.repo.Update(scanResult)
}

// DeleteScanResult 删除扫描结果
func (s *ScanService) DeleteScanResult(id uint) error {
	return s.repo.Delete(id)
}

// GetAllScanResults 获取所有扫描结果
func (s *ScanService) GetAllScanResults() ([]model.ScanResult, error) {
	return s.repo.GetAll()
}

// GetPaginatedScanResults 获取分页扫描结果列表
func (s *ScanService) GetPaginatedScanResults(page, pageSize int) (*utils.Pagination[model.ScanResult], error) {
	results, err := s.repo.GetPaginated(page, pageSize)
	return results, err
}

// GetScanResultsByProjectID 根据项目ID获取分页扫描结果
func (s *ScanService) GetScanResultsByProjectID(page, pageSize int, projectID string) (*utils.Pagination[model.ScanResult], error) {
	id, err := strconv.ParseUint(projectID, 10, 64)
	if err != nil {
		return nil, errors.New("无效的项目ID")
	}
	return s.repo.GetPaginatedByProjectID(page, pageSize, uint(id))
}
